{% extends "amdy_base.html" %}
{% load static %}
{% comment %} 额外引用的css文件 {% endcomment %}
{% block extcss %}
    <link rel="stylesheet" href="{% static 'css/exam_paper.css' %}">
{% endblock extcss %}
{% comment %} 标题 {% endcomment %}
{% block title %}
    {{block.super}}
{% endblock title %}
{% comment %} 菜单栏 {% endcomment %}
{% block topbar %}
    {% comment %} {% include "amdy_model.html" with model_type="topbar" name=user.nickname avatarSrc=user.icon %} {% endcomment %}
{% endblock topbar %}

{% block drawer %}
    {{block.super}}
{% endblock drawer %}

{% block mainlay %}

<div class="box_container">
    <div class="exam_box">
        <div class="problem-list">
            <div class="card">
                <div class="card_body">
                    <div style="font-size: 12px; font-weight: 700; background: rgb(239, 239, 239); padding: 10px 5px; color: rgb(10, 132, 255);">
                        科目一（多科目考试统计对比）
                    </div>
                    {% for key, question_list in questions.items %}
                        <div>
                            <strong>
                                {% if key == "single" %}
                                    <div class="card_title"> 单选题 <span style="float: right; font-size: 12px;">总{{question_list|length}}题</span></div>

                                {% elif key == "multiple" %}
                                    <div class="card_title"> 多选题 <span style="float: right; font-size: 12px;">总{{question_list|length}}题</span></div>
                                {% elif key == "true_or_false" %}
                                    判断题
                                {% elif key == "fill_in_the_blank" %}
                                    填空题
                                {% else %}
                                    {{ key }}
                                {% endif %}
                            </strong>
                            <div class="itemView">
                            {% for question in question_list %}
                                
                                    <div class="item" id={{question.id}} onclick="handleClick('{{ question.id }}',this)">
                                        <div class="num">{{forloop.counter0|add:1 }}</div>
                                        <div class="flag"></div>
                                    </div>
                                
                                {% comment %} <div>
                                    下标: {{ forloop.counter0 }}<br>  <!-- 获取基于 0 的下标 -->
                                    ID: {{ question.id }}<br>
                                    标题: {{ question.title }}<br>
                                    问题: {{ question.question }}<br>
                                    选项: {{ question.options }}<br>
                                    正确答案: {{ question.correct_answers }}<br>
                                    解释: {{ question.explanation }}<br>
                                    问题类型: {{ question.question_type }}<br>
                                    <hr>
                                </div> {% endcomment %}

                            {% endfor %}
                            </div>
                        </div>
                    {% endfor %}
                    {% comment %} <div>
                        
                        <div class="card-box">
                            <div class="">
                                <div class="item">
                                    <div class="num current">1</div>
                                    <div class="flag"></div>
                                </div>
                            </div>
                            <div class="">
                                <div class="item">
                                    <div class="num">2</div>
                                    <div class="flag"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div>
                        <div class="card_title"> 单选题 <span style="float: right; font-size: 12px;">总3题/共3分</span></div>
                        <div class="card-box">
                            <div class="">
                                <div class="item">
                                    <div class="num right">3</div>
                                    <div class="flag"></div>
                                </div>
                            </div>
                            <div class="">
                                <div class="item">
                                    <div class="num">4</div>
                                    <div class="flag"></div>
                                </div>
                            </div>
                            <div class="">
                                <div class="item">
                                    <div class="num">5</div>
                                    <div class="flag"></div>
                                </div>
                            </div>
                        </div>
                    </div> {% endcomment %}
                </div>
            </div>
        </div>
        <div class="problem">
            <div class="card" id="exam-body">
                <div class="card_body">
                    <div data-v-e42904d2="" id="qu-1469141533728583685" class="qu-box">
                        <div data-v-e42904d2="" class="">
                            <div data-v-e42904d2="" class="score-bar">
                                <div id="question_type" data-v-e42904d2="" style="flex-grow: 1;"></div>
                                <div data-v-e42904d2="" class="mark">
                                    <i data-v-e42904d2="" class="tooltip" aria-describedby="el-tooltip-3862" tabindex="0" style="cursor: pointer;"></i>
                                </div>
                            </div>
                            
                            <div data-v-e42904d2="" class="qu-item">
                                <div data-v-e42904d2="" class="qu-num">1</div>
                                
                                <div data-v-e42904d2="" class="qu-content">
                                    {% autoescape off %}
                                    <div id="question" data-v-e42904d2="">题目内容</div>
                                    {% endautoescape %}
                                </div>
                                
                            </div>
                            
                            
                            
                            
                            <div id="question_options" data-v-e42904d2="" class="qu-answer">
                                <div data-v-e42904d2="" class="qu-answer-item">
                                    <div data-v-e42904d2="" class="tag">A</div>
                                    <div data-v-e42904d2="" class="content">
                                        <div data-v-e42904d2="">四级</div>
                                    </div>
                                </div>
                                <div data-v-e42904d2="" class="qu-answer-item">
                                    <div data-v-e42904d2="" class="tag">B</div>
                                    <div data-v-e42904d2="" class="content">
                                        <div data-v-e42904d2="">三级</div>
                                    </div>
                                </div>
                                <div data-v-e42904d2="" class="qu-answer-item">
                                    <div data-v-e42904d2="" class="tag">C</div>
                                    <div data-v-e42904d2="" class="content">
                                        <div data-v-e42904d2="">二级</div>
                                    </div>
                                </div>
                                <div data-v-e42904d2="" class="qu-answer-item active">
                                    <div data-v-e42904d2="" class="tag">D</div>
                                    <div data-v-e42904d2="" class="content">
                                        <div data-v-e42904d2="">一级</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="submit-view">
            <div class="card">
                <div class="card_body">
                    <div class="row" style="margin-left: -5px; margin-right: -5px; text-align: center; line-height: 30px;">
                        <div class="col" style="padding-left: 5px; padding-right: 5px;"> 剩余时间 </div>
                        <div class="col" style="padding-left: 5px; padding-right: 5px;">
                            <span id="timer" data-v-1ccf9f5b="" class="time-cc">00分钟00秒</span>
                        </div>
                        <div class="col" style="padding-left: 5px; padding-right: 5px;">
                            <div class="divider"></div>
                        </div>
                        <div class="col" style="padding-left: 5px; padding-right: 5px;">
                            <button type="button" class="submit-btn" onclick="update()">
                                <span>提交试卷</span>
                            </button>
                        </div>
                        <div class="col" style="padding-left: 5px; padding-right: 5px;">
                            <div class="divider"></div>
                        </div>
                        <div class="col" style="padding-left: 5px; padding-right: 5px;">
                            <button type="button" class="button2" onclick="prevQuestion()">
                                <span>上一题</span>
                            </button>
                        </div>
                        <div class="col" style="padding-left: 5px; padding-right: 5px; padding-top: 20px;">
                            <button type="button" class="button2" onclick="nextQuestion()">
                                <span>下一题</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock mainlay %}

{% block extjs %}


<script>
    var questions={{questions|safe}};
    
    // 遍历对象，获取第一个键的第一个值的 id
    var currentId = null;  // 声明变量来存储第一个 id
    var currentKey = null;  // 声明变量来存储第一个键
    var currentIndex = null;  // 声明变量来存储第一个键的索引
    var currentType = null;  // 声明当前题目类型变量
    var currentAnswer={};
    var typeDiv=document.getElementById("question_type");
    var question_content=document.getElementById("question");
    var question_options=document.getElementById("question_options");
    // 初始化计时器
    let seconds = 0; // 计时的总秒数
    let timerInterval; // 计时器间隔
    // 计时器函数
    function startTimer() {
        // 每秒更新一次计时器
        timerInterval = setInterval(() => {
            seconds++; // 每次增加一秒
            updateTimerDisplay();
        }, 1000); // 1000ms = 1秒
    }
    

    function updateTimerDisplay() {
        // 计算分钟和秒
        const minutes = Math.floor(seconds / 60);
        const secs = seconds % 60;

        // 更新显示内容
        document.getElementById('timer').textContent = 
            `${String(minutes).padStart(2, '0')}分钟${String(secs).padStart(2, '0')}秒`;
    }

    // 当页面完全加载后开始计时
    window.onload = function() {
        startTimer();
    };



    // 遍历对象，获取第一个键的第一个值的 id
    for (var key in questions) {
        if (questions.hasOwnProperty(key)) {  // 确保这是对象的自有属性
            currentKey = key;  // 获取当前键
            if (questions[key].length > 0) {  // 检查数组是否有元素
                currentId = questions[key][0].id;  // 获取该数组第一个元素的 id
                currentIndex = 0;  // 获取该数组第一个元素的索引
                break;  // 找到后退出循环
            }
        }
    }

    

    // 输出结果
    console.log("currentKey:", currentKey);  // 输出第一个键
    console.log("currentIndex:", currentIndex);  // 输出第一个键的索引
    console.log("currentId:", currentId);  // 输出第一个找到的 id
    //找到class为item
    var elements = document.getElementsByClassName("item");
    // 遍历元素，找到对应 id 的元素
    for (var i = 0; i < elements.length; i++) {
        if (elements[i].id == currentId) {
            //elements[i].querySelector(".num").classList.add("current");  // 添加 active 类
            handleClick(currentId,elements[i]);
            break;  // 找到后退出循环
        }
    }
    //设置题目内容
    setQuestionContent(currentId);
    function insertImgs(srcList, targetElement) {
        for(var j=0;j<srcList.length;j++){
            var img = document.createElement("img");
            img.src = srcList[j];
            //设置图片最大宽度为100px
            img.style.maxWidth = "200px";
            //设置margin
            img.style.margin = "10px";
            //设置图片宽度为100%
            img.style.width = "100%";
            targetElement.appendChild(img);
        }
    }
    //设置题目内容
    function setQuestionContent(questionId) {
        // 遍历对象，找到对应 id 的题目内容
        for (var key in questions) {
            if (questions.hasOwnProperty(key)) {
                //遍历此类型题中的题目数组
                for (var i = 0; i < questions[key].length; i++) {
                    //如果找到对应id的题目
                    if (questions[key][i].id == questionId) {
                        
                        //记录当前题目类型
                        currentType=key;
                        // 将题目内容设置到页面中
                        //设置类型+标题
                        switch (key) {
                            case "single":
                                typeDiv.innerHTML = "[单选题]";
                                
                                break;
                            case "multiple":
                                typeDiv.innerHTML = "[多选题]";
                                // 当 expression 等于 value2 时执行的代码
                                break;
                            default:
                                typeDiv.innerHTML = key;
                                break;
                        }
                        
                        typeDiv.innerHTML+=" "+questions[key][i].title;

                        //设置内容
                        question_content.innerHTML="";
                        var question_dict=questions[key][i].question;
                        console.log("question_dict:",typeof question_dict, question_dict);
                        // 将 Markdown 转换为 HTML

                        //var html_content = marked(question_dict); // 调用 marked.js 转换
                        //console.log("html_content:",html_content);
                        //question_content.innerHTML =question_dict;
                        highlightContent(question_content,question_dict)
                        /*
                        //以下是原本以Object形式存储的显示代码

                        let questionObject;
                        //判断question_dict的类型
                        if(typeof question_dict!="object"){
                            questionObject=strToJSON(question_dict);
                        }else{
                            questionObject=question_dict;
                        }
                        
                        
                        console.log("questionObject:",typeof questionObject);  // 输出第一个找到的 id
                        
                        Object.keys(questionObject).forEach(function(key) {
                            console.log(key + ': ' + questionObject[key]);
                            if(key=="image_url"){
                                var srcList=questionObject[key];
                                insertImgs(srcList,question_content);
                                
                            }else{
                                question_content.innerHTML += key+": "+questionObject[key]+"<br>";
                            }
                            
                        })
                        
                        
                        */
                        
                        
                        //设置选项
                        question_options.innerHTML="";
                        console.log("questions[key][i].options:", questions[key][i].options);  // 输出第一个找到的 id
                        if(typeof questions[key][i].options!="object"){
                            var dictionary=strToJSON(questions[key][i].options);
                        }else{
                            var dictionary=questions[key][i].options;
                        }
                        console.log("dictionary:", typeof dictionary, dictionary);  // 输出第一个找到的 id
                        
                        
                        
                        Object.keys(dictionary).forEach(function(key2) {
                            console.log(key2 + ': ' + dictionary[key2]);
                            
                            var optionDiv = document.createElement("div");
                            optionDiv.className = "qu-answer-item";
                            optionDiv.onclick = function() {
                                handleSelect(questionId,key2,this) 
                            };
                            var optionTagDiv = document.createElement("div");
                            optionTagDiv.className = "tag";
                            //optionTagDiv.innerHTML = key;
                            switch (key2) {
                                case "option1":
                                    optionTagDiv.innerHTML= "A";
                                    optionTagDiv.style.color = "#0091ea";
                                    break;
                                case "option2":
                                    optionTagDiv.innerHTML= "B";
                                    optionTagDiv.style.color = "#00c853";
                                    break;
                                case "option3":
                                    optionTagDiv.innerHTML= "C";
                                    optionTagDiv.style.color = "#ffab00";
                                    break;
                                case "option4":
                                    optionTagDiv.innerHTML= "D";
                                    optionTagDiv.style.color = "#ff5722";
                                    break;
                                default:
                                    optionTagDiv.innerHTML= key2;
                            }

                            //判断这题有没有做过
                            if (currentAnswer[questionId] != null) {
                                //判断key2是否在currentAnswer[questionId]中，如果在，则设置选中状态
                                if (currentAnswer[questionId].includes(key2)){
                                    optionDiv.classList.add("active");
                                }
                            }

                            var optionContentDiv = document.createElement("div");
                            optionContentDiv.className = "content";
                            if(typeof dictionary[key2]=="string"){
                                optionContentDiv.innerHTML = dictionary[key2];
                            }else{
                                optionContentDiv.innerHTML = dictionary[key2].content;
                                if (dictionary[key2].image_url){
                                    var srcList=dictionary[key2].image_url;
                                    insertImgs(srcList,optionContentDiv);
                                }
                            }
                            optionDiv.appendChild(optionTagDiv);
                            optionDiv.appendChild(optionContentDiv);
                            

                            question_options.appendChild(optionDiv);
                        });
                        
                        
                        return;  // 找到后退出循环
                        /*
                        <div data-v-e42904d2="" class="qu-answer-item">
                            <div data-v-e42904d2="" class="tag">B</div>
                            <div data-v-e42904d2="" class="content">
                                <div data-v-e42904d2="">三级</div>
                            </div>
                        </div>
                        */
                        
                    }
                }
            }
        }

        //更新highlight
        setTimeout(() => {
            // 获取所有代码块
            const codeBlocks = question_content.querySelectorAll('pre code');
            
            // 对每个代码块进行高亮处理
            codeBlocks.forEach(block => {
                hljs.highlightBlock(block);
            });
    
            // 如果你需要行号，也可以初始化行号
            hljs.initLineNumbersOnLoad();
        }, 0); // 使用 0 延迟以确保在下一轮事件循环中执行
    }
    function strToJSON(question_dict) {
        let questionObject;
        // 原始字符串
        //let question_dict = " {'question': '问题内容', 'image_url': ['https://example.com/image1.jpg', 'https://example.com/image2.jpg']}";

        // 处理成有效的 JSON 字符串
        question_dict = question_dict
            .replace(/'/g, '"') // 将所有单引号替换为双引号
            .replace(/"(\w+)":/g, '"$1":') // 将键用双引号包围
            //将\转换成/
            .replace(/\\/g, '/');
        // 检查处理后的 JSON 字符串
        console.log("Converted JSON string:", question_dict);

        // 解析字符串为对象
        
        try {
            questionObject = JSON.parse(question_dict); // 解析为对象
        } catch (error) {
            console.error("Parsing error:", error);
        }

        // 输出结果
        if (questionObject) {
            console.log(questionObject);
        }
        return questionObject;
    }
                
    //题目点击事件
    function handleClick(questionId,that) {
        // 处理点击事件，例如调用其他函数或发送请求
        console.log("被点击的问题 ID:", questionId);
        setQuestionContent(questionId);
        // 显示选中效果
        // 查找 that 下的 num 类 div
        const numDiv = that.querySelector('.num');
        
        // 添加 current 类
        if (numDiv) {
            numDiv.classList.add('current'); // 添加 current 类
        }

        // 如果需要，还可以移除其他 num 类 div 上的 current 类
        const allNumDivs = document.querySelectorAll('.num');
        allNumDivs.forEach(div => {
            if (div !== numDiv) {
                div.classList.remove('current'); // 移除其他 num 类 div 的 current 类
            }
        });
        
        //hljs.highlightAll(); // 高亮代码
    }
    //遍历currentAnswer，如果currentAnswer[questionId]不为空，则将questionId对应item下的flag添加一个类为"done"
    function updateItemFlags() {
        console.log("updateItemFlags")
        //清空flag的down类
        const flags = document.querySelectorAll(".flag");
        
        flags.forEach(flag => {
            flag.classList.remove("down");
        });
        
        for (let questionId in currentAnswer) {
            console.log("questionId",questionId)
            if (currentAnswer[questionId].length > 0) {
                for (var i = 0; i < elements.length; i++) {
                    if (elements[i].id == questionId) {
                        elements[i].querySelector(".flag").classList.add("down");  // 添加 active 类
                        break;  // 找到后退出循环
                    }
                }
            }
        }
    }
    //上一题
    function prevQuestion() {
        console.log("prevQuestion")
        // 获取当前显示的题目
        const currentQuestion = document.querySelector('.num.current');
        console.log("currentQuestion",currentQuestion)
        //找到它的父节点的下一个兄弟节点
        const prevItem = currentQuestion.parentNode.previousElementSibling;
        // currentQuestion.parentNode.nextElementSibling;
        if(prevItem){
            console.log("prevItem",prevItem);
            handleClick(prevItem.id,prevItem);
        }else{
            const prevParent = currentQuestion.parentNode.parentNode.parentNode.previousElementSibling;
            console.log("prevParent",prevParent)
            if(prevParent){
                //在prevParent下找到class为item的最后一个子节点
                const lastChild = prevParent.querySelector(".item:last-child");
                if(lastChild){
                    handleClick(lastChild.id,lastChild);
                }else{
                    console.log("没有上一题")
                    aj.showTip("没有上一题");
                }
                //const lastChild = prevParent.lastElementChild;
                
            }else{
                console.log("没有上一题")
                aj.showTip("没有上一题");
            }
            
            return;
        }
        
        
        
    }
    //下一题
    function nextQuestion() {
        console.log("nextQuestion")
        // 获取当前显示的题目
        const currentQuestion = document.querySelector('.num.current');
        console.log("currentQuestion",currentQuestion)
        //找到它的父节点的下一个兄弟节点
        const nextItem = currentQuestion.parentNode.nextElementSibling;
        // currentQuestion.parentNode.nextElementSibling;
        if(nextItem){
            console.log("nextItem",nextItem)
            handleClick(nextItem.id,nextItem);
        }else{
            const nextParent = currentQuestion.parentNode.parentNode.parentNode.nextElementSibling;
            console.log("nextParent",nextParent)
            if(nextParent){
                //在prevParent下找到class为item的最后一个子节点
                const firstChild = nextParent.querySelector(".item:first-child");
                if(firstChild){
                    handleClick(firstChild.id,firstChild);
                }else{
                    console.log("没有下一题")
                    aj.showTip("没有下一题");
                }
                //const lastChild = prevParent.lastElementChild;
                
            }else{
                console.log("没有下一题")
                aj.showTip("没有下一题");
            }
        }
    }
    //选择事件
    function handleSelect(questionId, option,that) {

        console.log("被点击的问题 ID:", questionId);
        console.log("被点击的选项:", option);
        console.log("that is :",that);
        
        //将点击的选项保存到currentAnswer中
        if(currentAnswer[questionId]==null){
            currentAnswer[questionId]=[]
            currentAnswer[questionId].push(option);
            that.classList.add('active');
        }else if(currentAnswer[questionId].includes(option)){
            //在currentAnswer[questionId]中移除这个选项
            console.log("currentAnswer[questionId]",currentAnswer[questionId])
            var index = currentAnswer[questionId].indexOf(option); // 找到元素 1 的索引
            if (index !== -1) { // 确保元素存在于数组中
                currentAnswer[questionId].splice(index, 1); // 从索引位置删除 1 个元素
            }
            //清除这个选项的active类
            that.classList.remove('active')
        }else{
            //将这个选项添加到currentAnswer[questionId]中
            //将这个选项添加一个类active
            if(currentType=="single"){
                //找到that的兄弟节点，将他们的active类去掉
                var siblings = that.parentNode.children;
                for (var i = 0; i < siblings.length; i++) {
                    var sibling = siblings[i];
                    if (sibling !== that.parentNode) {
                        sibling.classList.remove('active');
                    }
                }
                currentAnswer[questionId]=[]
            }
            currentAnswer[questionId].push(option);
            that.classList.add('active');
            
        }
        //更新题目的flag
        updateItemFlags();
        console.log("currentAnswer is :",currentAnswer);
        
        
        
    }
    //更新
    function highlightContent(target,newContent) {
        console.log("update")
        /*
        newContent=`
            <p>这道题的描述部分，说明题目的内容和要求。</p>
            <pre class="codehilite"><code class="language-cpp">#include <iostream>
            using namespace std;

            int main() {
                cout << "Hello, World!" << endl;
                return 0;
            }
            </code></pre>
            `
        newContent2=` <pre class="codehilite"><code class="language-cpp">#include &lt;iostream&gt;
using namespace std;

int main() {
    cout &lt;&lt; &quot;Hello, World!&quot; &lt;&lt; endl;
    return 0;
}
</code></pre>`
*/
        target.innerHTML = newContent;
        // 使用 setTimeout 等待 DOM 更新
        setTimeout(() => {
            // 获取所有代码块
            const codeBlocks = target.querySelectorAll('pre code');
            
            // 对每个代码块进行高亮处理
            codeBlocks.forEach(block => {
                hljs.highlightBlock(block);
            });
        }, 0); // 使用 0 延迟以确保在下一轮事件循环中执行
        

    }

    // 如果需要代码高亮，启用以下代码
    document.addEventListener('DOMContentLoaded', function() {
        console.log("DOMContentLoaded");
        
        //hljs.highlightAll();  // 调用 Highlight.js 进行代码高亮
    });
</script>
{% endblock extjs %}